import { Service } from 'egg';
import { fn, col } from 'sequelize';

export default class PatentChart extends Service {

  async getTotal() {
    const { ctx } = this;

    const [
      patentNums,
      talentNums,
      productNums,
      organizationNums,
      companyNum
    ] = await Promise.all([
      ctx.model.Patent.findAll({
        attributes: [[fn('COUNT', col('id')), 'n_id']],
      }),
      ctx.model.Talent.findAll({
        attributes: [[fn('COUNT', col('id')), 'n_id']],
      }),
      ctx.model.Product.findAll({
        attributes: [[fn('COUNT', col('id')), 'n_id']],
      }),
      ctx.model.Organization.findAll({
        attributes: [[fn("COUNT", col("id")), "n_id"]],
      }),
      ctx.model.Company.findAndCountAll(),
    ]);
    const productNum = productNums.map(v => {
      const tem: any = v.toJSON();
      return tem.n_id;
    });
    const patentNum = patentNums.map(v => {
      const tem: any = v.toJSON();
      return tem.n_id;
    });
    const talentNum = talentNums.map(v => {
      const tem: any = v.toJSON();
      return tem.n_id;
    });
    const organizationNum = organizationNums.map(v => {
      const tem: any = v.toJSON();
      return tem.n_id;
    });
    return {
      patentNum: patentNum[0],
      talentNum: talentNum[0],
      productNum: productNum[0],
      organizationNum: organizationNum[0],
      companyNum: companyNum.count
    };
  }

  async getConversionStateChart() {
    const { ctx } = this;
    const result = Array(0);
    const State = ["已转化", "待转化", "未确定"];
    for (let i = 0; i < 3; i++) {
      const nums = await ctx.model.Patent.findAll({
        attributes: [[fn("COUNT", col("conversionType")), "n_conversionType"]],
        where: { conversionType: State[i] },
      });
      const num = nums.map(v => {
        const tem: any = v.toJSON();
        return tem.n_conversionType;
      });
      result.push({ value: num[0], name: State[i] });
    }
    return result;
  }

  async getAreaData() {
    const { ctx } = this;
    const name = await ctx.model.ApplicationArea.findAll();
    const areaName = name.map(v => {
      return v.name;
    });
    const number: number[] = [];
    for (let i = 0; i < name.length; i++) {
      const v = name[i];
      const nums = await ctx.model.Patent.findAll({
        attributes: [
          [fn("COUNT", col("fk_applicationArea")), "n_fk_applicationArea"],
        ],
        where: { fk_applicationArea: v.uuid },
      });
      const num = nums.map(v => {
        const tem: any = v.toJSON();
        return tem.n_fk_applicationArea;
      });
      number.push(num[0]);
    }
    // console.log("领域数量", number);
    return { name: areaName, number };
  }
}
